package erpc

import (
	"errors"
)

//msg: int32 len | int8 msg type | data
const (
	MsgUpload   = 1
	MsgDownload = 2
)

func Int2bytes(x int) []byte {
	b := make([]byte, 4)
	b[0] = byte((x >> 24) & 0xff)
	b[1] = byte((x >> 16) & 0xff)
	b[2] = byte((x >> 8) & 0xff)
	b[3] = byte((x) & 0xff)
	return b
}

func Bytes2Int(b []byte) int {
	if len(b) < 4 {
		return 0
	}
	var x = int(b[0]) << 24
	x |= int(b[1]) << 16
	x |= int(b[2]) << 8
	x |= int(b[3])
	return x
}

type Msg struct {
	Data    []byte
	MsgType byte
}

func NewMsg(data []byte, t uint8) *Msg {
	return &Msg{
		Data:    data,
		MsgType: t,
	}
}

func (m *Msg) Marshal() ([]byte, error) {
	buf := Int2bytes(len(m.Data) + 1)
	buf = append(buf, m.MsgType)
	buf = append(buf, m.Data...)
	return buf, nil
}
func Unmarshal(input []byte, size int) (*Msg, error) {
	msgType := input[0]
	if msgType != MsgUpload && msgType != MsgDownload {
		return nil, errors.New("error type")
	}
	data := input[1:]
	if len(data) != size-1 {
		return nil, errors.New("error len")
	}
	m := &Msg{}
	m.Data = data
	m.MsgType = msgType
	return m, nil

}
